package com.teachoa.bean;

import java.util.Date;
import java.util.List;

import com.jfinal.plugin.activerecord.Model;
import com.teachoa.enumtype.AskStatusEnum;

public class AskReply extends Model<AskReply> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7442540981173308343L;
	
	public static final AskReply dao = new AskReply();
	
	public List<AskReply> getReplysByAskId(String id) {
		return dao.find("select * from ask_reply where ask_id = ?", id);
	}
	
	public List<AskReply> getFinishReplysByAskId(String id) {
		return dao.find("select * from ask_reply where ask_id = ? and reply_time is not null order by reply_time asc", id);
	}
	
	public void deleteRelationsByAskId(String askId) {
		List<AskReply> replys = getReplysByAskId(askId);
		for(AskReply reply:replys) {
			reply.delete();
		}
	}
	
	public AskReply findAskReplyByAidAndRid(String askId, String userId) {
		return dao.findFirst("select * from ask_reply where ask_id = ? and replier_id = ?", askId, userId);
	}
	
	public void replyAsk(String askId, String userId, String text) {
		AskReply ar = findAskReplyByAidAndRid(askId, userId);
		ar.set("text", text);
		ar.set("reply_time", new Date());
		ar.update();
		Ask ask = Ask.dao.findById(askId);
		int status = ask.getInt("status");
		if(status==AskStatusEnum.WAIT.getCode()) {
			ask.set("status", AskStatusEnum.FINISHED.getCode());
			ask.update();
		}
	}

}
